package com.aliyun.alink.devicesdk.demo;

import com.aliyun.alink.linkkit.api.LinkKit;
import com.aliyun.alink.linksdk.cmp.core.base.AMessage;
import com.aliyun.alink.linksdk.cmp.core.base.ConnectState;
import com.aliyun.alink.linksdk.cmp.core.listener.IConnectNotifyListener;
import com.aliyun.alink.linksdk.tools.ALog;

import java.io.UnsupportedEncodingException;
import java.util.Vector;

import static com.aliyun.alink.devicesdk.demo.MqttSample.TAG;

public class SSHDevice {

    // ===================需要填写的参数开始===========================
    // 产品productKey
    private static String productKey = "a1OzdOsIu7q";
    //
    private static String deviceName = "fish_pi";
    // 设备密钥deviceSecret
    private static String deviceSecret = "v4m5ZlUgDp0PbCv4QKSn0lB4TtNKzBUA";
    // 消息通信的topic，无需创建和定义，直接使用即可
    private static String rrpcTopic = "/sys/" + productKey + "/" + deviceName + "/rrpc/request/+";
    // ssh 要访问的域名或IP
    private static String host = "192.168.0.105";
    // ssh 用户名
    private static String username = "pi";
    // ssh 密码
    private static String password = "w18734194202";
    // ssh 端口号
    private static int port = 22;
    // ===================需要填写的参数结束===========================

    public static void main(String[] args) throws InterruptedException {

        // 下行数据监听
        registerNotifyListener();

        // 建立连接
        Device.connect(productKey, deviceName, deviceSecret);

        // 订阅topic
        Device.subscribe(rrpcTopic);
    }

    public static void registerNotifyListener() {
        LinkKit.getInstance().registerOnNotifyListener(new IConnectNotifyListener() {
            @Override
            public boolean shouldHandle(String connectId, String topic) {
                // 只处理特定topic的消息
                if (topic.contains("/rrpc/request/")) {
                    return true;
                } else {
                    return false;
                }
            }

            @Override
            public void onNotify(String connectId, String topic, AMessage aMessage) {
                // 接收rrpc请求并回复rrpc响应
                try {
                    // 执行远程命令
                    String payload = new String((byte[]) aMessage.getData(), "UTF-8");
                    SSHShell sshExecutor = new SSHShell(host, username, password, port);
                    sshExecutor.execute(payload);

                    // 获取命令回显
                    StringBuffer sb = new StringBuffer();
                    Vector<String> stdout = sshExecutor.getStdout();
                    for (String str : stdout) {
                        sb.append(str);
                        sb.append("\n");
                    }


                    ALog.d(TAG, "执行命令1 ");

                    // 回复回显到服务端
                    String response = topic.replace("/request/", "/response/");
                    Device.publish(response, sb.toString());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onConnectStateChange(String connectId, ConnectState connectState) {
            }
        });
    }


    //获取命令执行结果
    public  String getCallBack(String payload){
        ALog.d(TAG, "执行命令21 ");
        ALog.d(TAG, payload);
        SSHShell sshExecutor = new SSHShell(host, username, password, port);
        sshExecutor.execute(payload);
        ALog.d(TAG, "执行命令结束 ");
        // 获取命令回显
        StringBuffer sb = new StringBuffer();
        Vector<String> stdout = sshExecutor.getStdout();
        for (String str : stdout) {
            sb.append(str);
            sb.append("\n");
        }
        ALog.d(TAG, "执行命令2 ");
        return String.valueOf(sb);
    }

}
